// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { getConfig, setConfig } from './readWrite';
import axios from 'axios';
import { debounce } from 'lodash';
// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
	// if (context.globalState.setKeysForSync()) {

	// }
	// console.log(getConfig())
	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('插件已经被激活');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('cocosautomaticrefresh.helloWorld', () => {
		// The code you place here will be executed every time your command is executed
		// Display a message box to the user
		vscode.window.showInformationMessage('Hello World from cocosAutomaticRefresh!');
	});
	const myEfficientFn = debounce(async (data1, data2) => {
		// 当 Ctrl + S 被按下时执行的操作
		console.log('Ctrl + S pressed');
		if (vscode.window.activeTextEditor) {
			const { document, selection } = vscode.window.activeTextEditor as vscode.TextEditor;
			document.save()
			let config = getConfig(context);
			if (document?.uri?.path && config.enabled == "enabled") {
				let url3X = `http://localhost:${config.port}/asset-db/refresh`;
				let url2X = `http://localhost:${config.port}/update-db`;
				// 3x刷新不成功就栓2x
				try {
					let data = await axios.get(url3X);
					if (data.data != 'success') {
						await axios.get(url2X);
					}
				} catch (error) {
					await axios.get(url2X);
				}
			} else {
				console.log(config.enabled, '没启动')
			}
		}
	}, 500);
	const myEfficientFn2 = debounce(async () => {
		let config = getConfig(context);
		let url3X = `http://localhost:${config.port}/asset-db/refresh`;
		let url2X = `http://localhost:${config.port}/update-db`;
		// 3x刷新不成功就栓2x
		try {
			let data = await axios.get(url3X);
			if (data.data != 'success') {
				await axios.get(url2X);
			}
		} catch (error) {
			await axios.get(url2X);
		}
	}, 500);
	let disposable2 = vscode.commands.registerCommand('extension.saveListener', myEfficientFn);
	let disposable3 = vscode.commands.registerCommand('cocosautomaticrefresh.refresh', myEfficientFn2)
	context.subscriptions.push(disposable2);
	context.subscriptions.push(disposable);
	context.subscriptions.push(disposable3);
	vscode.window.registerWebviewViewProvider('cocos-automatic-refresh', new DependenciesProvider(context));
	// vscode.window.createWebviewPanel('cocos-automatic-refresh',()=>{
	// 	console.log('激活')
	// })
	// console.log(getConfig())
}

// This method is called when your extension is deactivated
export function deactivate() { }

class DependenciesProvider implements vscode.WebviewViewProvider {
	context: vscode.ExtensionContext
	constructor(context: vscode.ExtensionContext) {
		this.context = context
	}
	// 实现 resolveWebviewView 方法，用于处理 WebviewView 的创建和设置
	resolveWebviewView(webviewView: vscode.WebviewView, context: vscode.WebviewViewResolveContext<unknown>, token: vscode.CancellationToken): void | Thenable<void> {
		console.log('打开')
		const config = getConfig(this.context);
		// 配置 WebviewView 的选项
		webviewView.webview.options = {
			enableScripts: true,
			localResourceRoots: [this.context.extensionUri]
		};

		// 设置 WebviewView 的 HTML 内容，可以在这里指定要加载的网页内容
		webviewView.title = 'Cocos自动刷新';

		// webviewView.webview.s = true;
		webviewView.webview.html = getHtml(config);
		webviewView.webview.onDidReceiveMessage(message => {
			console.log(message.text, 'message 收到消息')
			if (message.command == 'updata') {
				setConfig(this.context, message.text as any);
				vscode.window.showInformationMessage(`配置 保存成功 , 是否开启：${this.context, message.text.enabled ? "是" : "否"},端口：${message.text.port}`);
			} else if (message.command == 'getData') {
				let data = getConfig(this.context)
				webviewView.webview.postMessage({ command: 'returnData', arg1: data.enabled, arg2: data.port })
			}

		}, undefined, this.context.subscriptions);
	}
}

function getHtml(config: any) {
	return ` 
	<html>
	<head></head>
	<body>
		<form method="get" onsubmit="return mySubmit(this)">
			<div style="display: flex;justify-content: space-between;">
				<div>是否开启</div>
				<div>
					<input type="checkbox" id="enabled" name="enabled"
						value="enabled" ${config.enabled == "enabled" ? 'checked' : ''}>
				</div>
			</div>
			<div
				style="display: flex;justify-content: space-between;margin-top: 20px;">
				<div>默认端口</div>
				<div>
					<input id="port" type="number" 
						id="port" name="port" value="${config.port}">
				</div>
			</div>
			<div style="display: flex;justify-content: end;">
				<button id="btn" style="margin-top: 20px;">确认修改</button>
			</div>
		</form>
		<script>
		const vscode = acquireVsCodeApi();
		console.log('触发11')
		vscode.postMessage({
			command: 'getData'
		})
		function mySubmit(form) {
			console.log('触发')
			//定义formData对象
			let formData = new FormData(form);
			//获取值，因为get只能获取一个值，而这里是多选框，所以这里使用getAll方法
			let enabled = formData.get('enabled');
			let port = formData.get('port');
			console.log(enabled);
			console.log(port);
			vscode.postMessage({
				command: 'updata',
				text: {enabled,port}
			})
			alert('保存成功')
			// 页面数据不进行提交，只是进行测试
			return false;
		}
		const initForm = (enabled,port) =>{
            document.getElementById("enabled").checked = enabled;
            document.getElementById("port").value = port;
        }
		window.addEventListener("message", (evsent)=>{
			console.log(event,'event')
			if (event.data.command === 'returnData') {
				initForm(event.data.arg1,event.data.arg2)
			}
		})
		</script>
	</body>
</html>
`
}